package com.azxc.rapid.auth.utils;

import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author linym
 * @create-day 2018-08-14 10:56
 */
public class EncryptUtils {

    static final String HMAC_MD5_NAME  = "HmacMD5";
    /**
     * 用MD5算法进行加密
     *
     * @param str 需要加密的字符串
     * @return MD5加密后的结果
     */
    public static String encodeMD5String(String str) {
        return encode(str, "MD5");
    }

    /**
     * 用SHA算法进行加密
     *
     * @param str 需要加密的字符串
     * @return SHA加密后的结果
     */
    public static String encodeSHAString(String str) {
        return encode(str, "SHA");
    }

    public static String encodeHMACMD5String(String  MACKEY,String source) throws Exception {
        byte[] result =encryptionHMAC(MACKEY,source);
        return change(result);
    }

    /**
     * HMAC加密
     * @return
     * @throws Exception
     */
    static byte[] encryptionHMAC(String  MACKEY,String source) throws Exception {
        SecretKey secretKey = new SecretKeySpec(MACKEY.getBytes("UTF-8"), HMAC_MD5_NAME);
        Mac mac = Mac.getInstance(HMAC_MD5_NAME);
        mac.init(secretKey);
        mac.update(source.getBytes());
        return mac.doFinal();
    }

    /**
     *  BASE64加密
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    private static String encode(String str, String method) {
        MessageDigest md = null;
        String dstr = null;
        try {
            md = MessageDigest.getInstance(method);
            md.update(str.getBytes());
            dstr = new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return dstr;
    }

    /**
     * base64编码
     * @param source
     * @return
     * @throws Exception
     */
    static String encodeBase64(byte[] source) throws Exception{
        return new String(Base64.encode(source));
    }

    /**
     * base64编码
     * @param source
     * @return
     * @throws Exception
     */
    static String encodeBase64ByUtf8(byte[] source) throws Exception{
        return new String(Base64.encode(source), "UTF-8");
    }


    public static String change(byte[] result){
        StringBuilder sb=new StringBuilder();
        for(byte b : result){
            if(Integer.toHexString(0xFF & b).length()==1){
                //System.out.print("0"+Integer.toHexString(0xFF & b));
                sb.append("0"+Integer.toHexString(0xFF & b));
            }

            else{
                //System.out.print(Integer.toHexString(0xFF & b));
                sb.append(Integer.toHexString(0xFF & b));
            }
        }
        return sb.toString();
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
    /**
     * sha256_HMAC加密
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }
        return hash;
    }

  /*  public static void main(String[] args) throws Exception {
        String  MACKEY="6186ec9223b8f8e3fe28b5f5c831427ed99950a6";
        String source="accesskey=6d8f62fd-3086-46e3-a0ba-c66a929c24e2&method=getAccountInfo";
        byte[] result =encryptionHMAC(MACKEY,source);
        String r=encodeHMACMD5String(MACKEY,source);
        System.out.println(r);
    }*/

}
